package com.liao.product.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liao.common.constant.order.OrderEnum;
import com.liao.common.constant.order.WareLockStatusEnum;
import com.liao.common.constant.product.ProductImgsTypeEnum;
import com.liao.common.doc.ProductDoc;
import com.liao.common.entity.member.UserAddressEntity;
import com.liao.common.entity.member.UserEntity;
import com.liao.common.entity.order.OrdersEntity;
import com.liao.common.entity.product.*;
import com.liao.common.to.mq.StockLockedTo;
import com.liao.common.to.order.OrderTo;
import com.liao.common.utils.PageUtils;
import com.liao.common.utils.Query;
import com.liao.common.utils.Result;
import com.liao.common.vo.product.ProductDetailVO;
import com.liao.common.vo.product.ProductSaveReq;
import com.liao.product.dao.ProductDao;
import com.liao.product.feign.MemberFeignService;
import com.liao.product.feign.OrderFeignService;
import com.liao.product.feign.SearchFeignService;
import com.liao.product.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Service("productService")
public class ProductServiceImpl extends ServiceImpl<ProductDao, ProductEntity> implements ProductService {

    @Autowired
    private ProductImgsService productImgsService;

    @Autowired
    ProductAttributeService productAttributeService;

    @Autowired
    SkuService skuService;

    @Autowired
    SkuAttributeService skuAttributeService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    WareTaskService wareTaskService;


    @Autowired
    CategoryService categoryService;

    @Autowired
    SearchFeignService searchFeignService;

    @Autowired
    private ProductService productService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<ProductEntity> productEntityQueryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!key.isEmpty()) {
            productEntityQueryWrapper.eq("product_id", key).or().like("title", key);
        }

        IPage<ProductEntity> page = this.page(
                new Query<ProductEntity>().getPage(params),
                productEntityQueryWrapper
        );


        return new PageUtils(page);
    }


    @Override
    public Integer getProductCountByCategoryId(Integer CategoryId) {
        QueryWrapper<ProductEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", CategoryId);
        return this.count(queryWrapper);
    }

    @Transactional
    @Override
    public void unlockStock(StockLockedTo to) {

        String orderId = to.getOrderId();
        Long stockId = to.getId();

        Result<OrdersEntity> result = orderFeignService.getOrderByOrderId(orderId);
        WareTaskEntity task = wareTaskService.getTaskById(stockId);
        Integer code = result.getCode();

        if (code == 200) {
//            OrderTo order = (OrderTo) r.get("data");

            // 将list中的数据转成json字符串
//            String jsonObject = JSON.toJSONString(r.get("data"));
//            System.out.println(jsonObject);
//            //将json转成需要的对象
//            OrderTo order = JSONObject.parseObject(jsonObject, OrderTo.class);
            OrdersEntity order = result.getData();


            if (order == null || OrderEnum.ORDER_STATUS_CANCLED.equals(order.getOrderStatus())) {
                //订单未支付，解锁库存
                if (WareLockStatusEnum.LOCKED.equals(task.getLockStatus())) {

                    unLockStock(task.getId(), task.getSkuId(), task.getSkuNum());
                }


            }
        } else {
            new RuntimeException("orderFeignService远程调用失败");
        }

    }


    /**
     * 库存解锁
     * 订单解锁触发，防止库存解锁消息优先于订单解锁消息到期，导致库存无法解锁
     */
    @Transactional
    @Override
    public void unLockStock(OrderTo order) {
        // 1.根据订单号查询库存锁定工作单
        String orderId = order.getOrderId();// 订单号
        List<WareTaskEntity> wareTaskEntityList = wareTaskService.list(new QueryWrapper<WareTaskEntity>()
                .eq("order_id", orderId));

        // 2.按照工作单查询未解锁的库存，进行解锁
        wareTaskEntityList.forEach(wareTaskEntity -> {
            // 3.解锁库存
            unLockStock(wareTaskEntity.getId(), wareTaskEntity.getSkuId(), wareTaskEntity.getSkuNum());

        });

    }

    @Override
    public ProductDetailVO getDetail(Integer id) {
        ProductDetailVO detail = new ProductDetailVO();
        //1.获取商品的基本信息
        ProductEntity product = productService.getOne(new QueryWrapper<ProductEntity>().eq("product_id", id));
        BeanUtils.copyProperties(product, detail);
        //2.获取商品图片信息
        List<ProductImgsEntity> productImgsEntityList = productImgsService.list(new QueryWrapper<ProductImgsEntity>().eq("spu_id", id));
        List<String> bannerImgs = new ArrayList<>();
        List<String> descImgs = new ArrayList<>();
        productImgsEntityList.forEach(productImgsEntity -> {
            if (ProductImgsTypeEnum.BANNER_TYPE == productImgsEntity.getImgType()) {
//                bannerImgs.add(productImgsEntity.getImgUrls());
                List<String> list = JSON.parseArray(productImgsEntity.getImgUrls(), String.class);
                bannerImgs.addAll(list);
            }
            if (ProductImgsTypeEnum.DESC_TYPE == productImgsEntity.getImgType()) {
                List<String> list = JSON.parseArray(productImgsEntity.getImgUrls(), String.class);
                descImgs.addAll(list);
            }
        });
        detail.setDescImgs(descImgs);
        detail.setBannerImgs(bannerImgs);
        //3.获取商品属性信息
        List<ProductAttributeEntity> attrs = productAttributeService.list(new QueryWrapper<ProductAttributeEntity>().eq("product_id", id));
        detail.setAttrs(attrs);
        //4.获取商品规格信息
        List<SkuAttributeEntity> skuAttributeEntityList = skuAttributeService.list(new QueryWrapper<SkuAttributeEntity>().eq("product_id", id));
        //遍历为转化成数组赋值

        for (SkuAttributeEntity skuAttributeEntity : skuAttributeEntityList) {
            List<String> list = JSON.parseArray(skuAttributeEntity.getAttrValues(), String.class);
            skuAttributeEntity.setAttributeValueArr((ArrayList) list);
        }

        detail.setSkuAttrs(skuAttributeEntityList);
        //5.获取sku商品
        List<SkuEntity> skus = skuService.list(new QueryWrapper<SkuEntity>().eq("product_id", id));
        detail.setSkus(skus);

        //6.获取用户收货地址
        //用户登录则获取地址，否则不设置地址
        if (StpUtil.isLogin()) {
            UserEntity User = (UserEntity) StpUtil.getSession().get(SaSession.USER);
            List<UserAddressEntity> address = memberFeignService.getAddress(User.getUserId());
            detail.setAddressList(address);
        }

//         7.获取同类推荐商品
        Result<List<ProductDoc>> result = searchFeignService.relevant(detail.getProductId().toString());
        if (result.getCode() == 200) {
            List<ProductDoc> relevant = result.getData();
            detail.setSimilarProducts(relevant);
        }


        return detail;
    }


    @Transactional
    @Override
    public void save(ProductSaveReq saveReq) {
        System.out.println(saveReq);

//        1.提交商品基本信息
        ProductEntity productEntity = new ProductEntity();
        BeanUtils.copyProperties(saveReq, productEntity);
        productEntity.setViewCount(0);
        this.save(productEntity);
        ArrayList<String> bannerImgs = saveReq.getBannerImgs();
        ArrayList<String> descImgs = saveReq.getDescImgs();

//        1.1提交商品的图片
        //        banner图片处理
        ProductImgsEntity productImgsEntity = new ProductImgsEntity();
        productImgsEntity.setSpuId(productEntity.getProductId());
        productImgsEntity.setImgType(ProductImgsTypeEnum.BANNER_TYPE);
        productImgsEntity.setImgUrls(JSON.toJSONString(bannerImgs));
        productImgsService.save(productImgsEntity);
//        商品详情图片处理
        ProductImgsEntity descImgEntity = new ProductImgsEntity();
        descImgEntity.setSpuId(productEntity.getProductId());
        descImgEntity.setImgType(ProductImgsTypeEnum.DESC_TYPE);
        descImgEntity.setImgUrls(JSON.toJSONString(descImgs));
        productImgsService.save(descImgEntity);


//        2.提交商品属性信息
        ArrayList<ProductAttributeEntity> attrs = saveReq.getAttrs();

//        为属性赋值标记商品的编号
        attrs.forEach(attr -> {
            attr.setProductId(productEntity.getProductId());
        });

        System.out.println(attrs);
        productAttributeService.saveBatch(attrs);


//        3.提交销售属性
        ArrayList<SkuAttributeEntity> skuAttrs = saveReq.getSkuAttrs();
        System.out.println(skuAttrs);

//        为属性赋值标记商品的编号
        skuAttrs.forEach(attr -> {
            attr.setProductId(productEntity.getProductId());
            attr.setAttrValues(JSON.toJSONString(attr.getAttributeValueArr()));
        });
        skuAttributeService.saveBatch(skuAttrs);


//      4.提交sku信息
        ArrayList<SkuEntity> skus = saveReq.getSkuList();
        skus.forEach(sku -> {
            sku.setProductId(productEntity.getProductId());
            sku.setSkuCode(UUID.randomUUID().toString());
            sku.setSales(0);
//            拼接sku属性json

//            JSONObject jsonObj = new JSONObject();
//            sku.getSkuAttributeValueArr().forEach(skuAttributeEntity -> {
//                jsonObj.put(skuAttributeEntity.getAttrName(), skuAttributeEntity.getAttrValues());
//            });
            StringBuilder stringBuilder = new StringBuilder();
            sku.getSkuAttributeValueArr().forEach(skuAttributeEntity -> {
                stringBuilder.append(skuAttributeEntity.getAttrValues() + ",");
            });
            // 删除最后一个逗号（如果存在）
            if (stringBuilder.length() > 0) {
                stringBuilder.setLength(stringBuilder.length() - 1);
            }
            
            sku.setAttributes(stringBuilder.toString());

        });
        System.out.println(skus);
        skuService.saveBatch(skus);

//       封装信息 上传到es
        ProductDoc productDoc = new ProductDoc();
        BeanUtils.copyProperties(productEntity, productDoc);
        productDoc.setSkuAttr(skus.toString());
        //获取分类信息
        CategoryEntity category = categoryService.getById(productEntity.getCategoryId());
        productDoc.setCategoryName(category.getName());

        ArrayList<ProductDoc> productDocArrayList = new ArrayList<>();
        productDocArrayList.add(productDoc);

        searchFeignService.productStatusUp(productDocArrayList);
//        throw new RuntimeException("测试异常");
    }


    /**
     * 库存解锁
     * 1.sql执行释放锁定
     * 2.更新库存工作单状态为已解锁
     *
     * @param skuId
     * @param count
     */
    public void unLockStock(Long taskId, Integer skuId, Integer count) {


        skuService.unlockStock(skuId, count);


        // 2.更新工作单的状态 已解锁
        WareTaskEntity task = new WareTaskEntity();
        task.setId(taskId);
        task.setLockStatus(WareLockStatusEnum.UNLOCKED);
        wareTaskService.updateById(task);

    }
}